﻿using Segex;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace RegexTester
{
    public partial class SegexTester : Form
    {
        private SegexGenerator generator = new SegexGenerator();

        public SegexTester()
        {
            InitializeComponent();
        }

        private void txt_InputExpression_TextChanged(object sender, EventArgs e)
        {
            txt_InputData.Select(0, 0);

            SegexGeneratorOutput op = generator.Generate(txt_InputExpression.Text);

            //Update preprocessor output
            txt_PreProsOut.Text = op.Preprocessor;

            try
            {

                //Update compiler output
                if (op.IsError)
                {
                    UpdateTextBox(txt_ParserGenOutput, op.Output, true);
                }
                else
                {
                    UpdateTextBox(txt_ParserGenOutput, op.Output, false);
                }

                //Try to parse resulting regular expression
                Regex regex ;

                try
                {
                    regex = new Regex(op.Result, RegexOptions.Multiline);
                    txt_GeneratedRegex.BackColor = SystemColors.Window;
                    UpdateTextBox(txt_GeneratedRegex, op.Result, false);
                }
                catch
                {
                    UpdateTextBox(txt_GeneratedRegex, op.Result, true);
                    return;
                }

                //Valid expression, use it
                Match match = regex.Match(txt_InputData.Text);

                if (match.Success)
                {
                    Group g = match.Groups["CAPTURE"];

                    if (g != null && g.Success)
                    {
                        txt_InputData.Select(g.Index, g.Length);
                        txt_Output.Text = g.Value;
                    }
                    else
                    {
                        txt_InputData.Select(match.Index, match.Length);
                        txt_Output.Text = match.Value;
                    }
                }
            }
            catch
            {

            }


        }

        private void UpdateTextBox(TextBox textbox, string data, bool isError)
        {
            textbox.Text = data;
            if (isError)
                textbox.BackColor = Color.Red;
            else
                textbox.BackColor = SystemColors.Control;
        }
    }


}
